package Test.View;
import Test.UserMapper;
import Test.User;
import Utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import javax.swing.*;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.Socket;
import java.util.Arrays;
import java.util.List;

import static Test.Util.*;
import static org.apache.commons.io.FileUtils.readFileToByteArray;

public class ChatPage extends JFrame {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper usermapper = sqlSession.getMapper(UserMapper.class);
    private JList<String> friendList;
//    private JTextArea chatArea;
    private JTextPane chatArea;  // 将 JTextArea 替换成 JTextPane
    private JTextField inputField;
    private JButton sendButton, addButton, sendImageButton;
    private DefaultListModel<String> listModel;
    public User CurrentlyFriend=usermapper.GetUserByNickName("阿里木");
    public ChatPage(String username) throws IOException {
        super("Chat Page");
        String serverIP = "60.204.251.108"; // 替换成你的云服务器公网IP
        int serverPort = 3915;
        Socket socket = new Socket(serverIP, serverPort);
        System.out.println("已连接到服务器.");
        chatArea = new JTextPane();

        StyledDocument doc = chatArea.getStyledDocument();
        SimpleAttributeSet defaultStyle = new SimpleAttributeSet();
        StyleConstants.setForeground(defaultStyle, Color.BLACK);
        StyleConstants.setFontSize(defaultStyle, 14);
        doc.setParagraphAttributes(0, doc.getLength(), defaultStyle, false);
        // 创建接收消息的线程
        Thread receiveThread = new Thread(() -> {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
                String serverResponse;
                while ((serverResponse = reader.readLine()) != null) {
                    System.out.println("服务器返回的是: " + serverResponse);
                    String mayimage = splitString(serverResponse).get(1);
                    byte[] bytes = parseBinaryArray(mayimage);
                    if (bytes==null){
                        System.out.println(111111);
                        appendToChatArea("<" +usermapper.GetNickNameByIP(splitString(serverResponse).get(0))+">:->"+splitString(serverResponse).get(1), Color.RED);

                    }else {
                        System.out.println("-------------------------------------第1-------------------------------------");
//                    System.out.println(Arrays.toString(bytes));
                        // 创建 ImageIcon 对象
                        ImageIcon originalIcon = new ImageIcon(bytes);
                        // 调整图片大小
                        Image image = originalIcon.getImage();
                        Image scaledImage = image.getScaledInstance(200, -1, Image.SCALE_DEFAULT); // 200为宽度，-1表示按比例缩放高度
                        ImageIcon scaledIcon = new ImageIcon(scaledImage);
                        JLabel imageLabel = new JLabel(scaledIcon);
                        System.out.println("来了");
                        // 将图片添加到聊天区域 chatArea 中
                        chatArea.insertComponent(imageLabel);
                        System.out.println("-------------------------------------第1-------------------------------------");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        receiveThread.start();
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
        // 创建好友列表
        listModel = new DefaultListModel<>();
        friendList = new JList<>(listModel);
        JScrollPane friendListPane = new JScrollPane(friendList);
        friendListPane.setPreferredSize(new Dimension(200, 0));
        friendList.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent evt) {
                if (evt.getClickCount() >=1) {
                    // 双击事件
                    String selectedFriend = friendList.getSelectedValue();
//                    System.out.println(selectedFriend);
                    CurrentlyFriend = usermapper.GetUserByNickName(selectedFriend);
                }
            }
        });
        User user = usermapper.GetUserByNickName(username);
        List<User> users = usermapper.GetFriend(user);
        for (User user1:users){
            listModel.addElement(user1.getNickname());
        }
        // 聊天区域
        chatArea.setEditable(false);
        JScrollPane chatScrollPane = new JScrollPane(chatArea);
        // 输入区域与发送按钮
        JPanel inputPanel = new JPanel();
        inputField = new JTextField(20);
        sendButton = new JButton("Send");
        sendImageButton = new JButton("Send Image");
//        inputField.setText("66666");
        inputPanel.add(inputField);
        inputPanel.add(sendButton);
        inputPanel.add(sendImageButton);
        // 发送消息
        sendButton.addActionListener(e -> {
            String message = inputField.getText().trim();
            if (!message.isEmpty()) {
                appendToChatArea("Friend: " +username+":->"+message, Color.BLUE);
                try {
                    PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"), true);
                    writer.println(CurrentlyFriend.getIP() + "@" + message); // 发送消息到服务器
                } catch (IOException ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(this, "消息发送失败！", "错误", JOptionPane.ERROR_MESSAGE);
                }
                inputField.setText(""); // 清空输入框
            }
        });
        inputField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    sendButton.doClick();
                }
            }
        });
        // 发送图片
        sendImageButton.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            int result = fileChooser.showOpenDialog(this);
            if (result == JFileChooser.APPROVE_OPTION) {
                String filePath = fileChooser.getSelectedFile().getAbsolutePath();
                try {
                    byte[] fileData = readFileToByteArray(new File(filePath));
//                    System.out.println(Arrays.toString(fileData));

                    // 创建 ImageIcon 对象
                    ImageIcon originalIcon = new ImageIcon(fileData);

                    // 调整图片大小
                    Image image = originalIcon.getImage();
                    Image scaledImage = image.getScaledInstance(200, -1, Image.SCALE_DEFAULT); // 200为宽度，-1表示按比例缩放高度
                    ImageIcon scaledIcon = new ImageIcon(scaledImage);
                    JLabel imageLabel = new JLabel(scaledIcon);
                    PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"), true);
                    writer.println(CurrentlyFriend.getIP() + "@" + Arrays.toString(fileData)); // 发送消息到服务器
                    // 将图片添加到聊天区域 chatArea 中
                    chatArea.insertComponent(imageLabel);

                    // 在聊天区域中显示图片
                    appendToChatArea("", Color.BLACK); // 添加一个空行，用于显示图片
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        // 添加好友按钮
        addButton = new JButton("添加好友");
        addButton.addActionListener(e -> {
            String friendName = JOptionPane.showInputDialog(this, "输入好友账号:");
            if (friendName != null && !friendName.isEmpty()) {
                usermapper.AddFriend(usermapper.GetUserByNickName(username).getUserID(),usermapper.GetUserByNickName(friendName).getUserID());
                System.out.println("添加成功");
                listModel.addElement(friendName);
            }
        });
        // 将组件添加到窗口
        add(friendListPane, BorderLayout.WEST);
        add(chatScrollPane, BorderLayout.CENTER);
        add(inputPanel, BorderLayout.SOUTH);
        add(addButton, BorderLayout.NORTH);
        setVisible(true);
    }
    private void appendToChatArea(String text, Color color) {
        StyledDocument doc = chatArea.getStyledDocument();
        SimpleAttributeSet keyWord = new SimpleAttributeSet();
        StyleConstants.setForeground(keyWord, color);
        try {
            // 在末尾添加文本
            doc.insertString(doc.getLength(), text + "\n", keyWord);
            // 滚动到末尾
            chatArea.setCaretPosition(doc.getLength());
        } catch (Exception e) {
            System.out.println("出错了");
        }
    }
}